import React, { useState, useEffect } from 'react';
import { 
  BarChart3, 
  Shield, 
  Users, 
  Database, 
  AlertTriangle, 
  TrendingUp, 
  Download, 
  RefreshCw,
  CheckCircle,
  XCircle
} from 'lucide-react';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { monitorApi } from '../../services/monitor';
import type { MonitoringSummaryReport } from '../../types/monitor';

interface MonitoringSummaryReportProps {
  refreshInterval?: number;
}

const MonitoringSummaryReportComponent: React.FC<MonitoringSummaryReportProps> = ({
  refreshInterval = 60000 // 1分钟刷新一次
}) => {
  const [loading, setLoading] = useState(false);
  const [report, setReport] = useState<MonitoringSummaryReport | null>(null);
  const [error, setError] = useState<string | null>(null);

  // 获取监控摘要报告
  const fetchSummaryReport = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await monitorApi.getMonitoringSummaryReport();
      if (response.success) {
        setReport(response.data);
      }
    } catch (error) {
      console.error('获取监控摘要报告失败:', error);
      setError('获取监控摘要报告失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSummaryReport();
    const interval = setInterval(fetchSummaryReport, refreshInterval);
    return () => clearInterval(interval);
  }, [refreshInterval]);

  // 导出报告
  const exportReport = () => {
    if (!report) return;
    
    const reportData = {
      ...report,
      export_time: new Date().toISOString()
    };
    
    const blob = new Blob([JSON.stringify(reportData, null, 2)], {
      type: 'application/json'
    });
    
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `kafka-monitoring-report-${new Date().toISOString().split('T')[0]}.json`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 获取健康状态颜色
  const getHealthColor = (health: string) => {
    switch (health.toLowerCase()) {
      case 'healthy': return 'text-green-500';
      case 'warning': return 'text-yellow-500';
      case 'critical': return 'text-red-500';
      default: return 'text-gray-500';
    }
  };

  // 格式化字节数
  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 准备Top Topics图表数据
  const prepareTopTopicsData = () => {
    if (!report?.top_topics) return [];
    
    return report.top_topics.slice(0, 10).map(topic => ({
      topic: topic.topic_name,
      rate: topic.production_rate,
      partitions: topic.partition_count
    }));
  };

  // 准备消费者组状态分布数据
  const prepareConsumerGroupStatusData = () => {
    if (!report) return [];
    
    const statusCount = {
      normal: report.cluster_overview.active_consumer_groups - report.problematic_consumer_groups.length,
      problematic: report.problematic_consumer_groups.length
    };
    
    return [
      { name: '正常', value: statusCount.normal, color: '#10b981' },
      { name: '有问题', value: statusCount.problematic, color: '#f59e0b' }
    ];
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        <span className="ml-2">加载中...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-4">
        <div className="flex items-center">
          <AlertTriangle className="w-5 h-5 text-red-500 mr-2" />
          <span className="text-red-700">{error}</span>
        </div>
      </div>
    );
  }

  if (!report) {
    return (
      <div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
        <div className="text-center text-gray-500">暂无数据</div>
      </div>
    );
  }

  const topTopicsData = prepareTopTopicsData();
  const consumerGroupStatusData = prepareConsumerGroupStatusData();

  return (
    <div className="space-y-6">
      {/* 报告头部 */}
      <div className="bg-white rounded-lg shadow-sm border p-6">
        <div className="flex justify-between items-center">
          <div>
            <div className="flex items-center">
              <BarChart3 className="w-6 h-6 text-blue-500 mr-2" />
              <h1 className="text-2xl font-bold text-gray-900">Kafka 集群监控摘要报告</h1>
            </div>
            <p className="text-gray-600 mt-1">
              报告时间: {new Date(report.report_time).toLocaleString()}
            </p>
          </div>
          <div className="flex items-center space-x-3">
            <button
              onClick={fetchSummaryReport}
              disabled={loading}
              className="flex items-center px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 disabled:opacity-50"
            >
              <RefreshCw className={`w-4 h-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
              刷新报告
            </button>
            <button
              onClick={exportReport}
              className="flex items-center px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600"
            >
              <Download className="w-4 h-4 mr-2" />
              导出报告
            </button>
          </div>
        </div>
      </div>

      {/* 集群概览 */}
      <div className="bg-white rounded-lg shadow-sm border p-6">
        <h2 className="text-lg font-medium text-gray-900 mb-4">集群概览</h2>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="text-center">
            <div className={`text-2xl font-bold ${getHealthColor(report.cluster_overview.overall_health)}`}>
              {report.cluster_overview.overall_health === 'healthy' ? (
                <CheckCircle className="w-8 h-8 mx-auto mb-2" />
              ) : (
                <XCircle className="w-8 h-8 mx-auto mb-2" />
              )}
              {report.cluster_overview.overall_health}
            </div>
            <p className="text-sm text-gray-600">集群健康状态</p>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">{report.cluster_overview.broker_count}</div>
            <p className="text-sm text-gray-600">Broker数量</p>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">{report.cluster_overview.topic_count}</div>
            <p className="text-sm text-gray-600">Topic数量</p>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">
              {report.cluster_overview.active_consumer_groups} / {report.cluster_overview.consumer_group_count}
            </div>
            <p className="text-sm text-gray-600">活跃消费者组</p>
          </div>
        </div>
      </div>

      {/* 性能摘要 */}
      <div className="bg-white rounded-lg shadow-sm border p-6">
        <h2 className="text-lg font-medium text-gray-900 mb-4">性能摘要</h2>
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-500">
              {(report.performance_summary.total_production_rate_per_minute || 0).toFixed(1)}
            </div>
            <p className="text-sm text-gray-600">集群生产速率 (msg/min)</p>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-500">
              {formatBytes(report.performance_summary.total_bytes_per_minute || 0)}/min
            </div>
            <p className="text-sm text-gray-600">集群字节速率</p>
          </div>
          <div className="text-center">
            <div className={`text-2xl font-bold ${
              report.performance_summary.total_consumer_lag > 10000 ? 'text-red-500' : 'text-green-500'
            }`}>
              {report.performance_summary.total_consumer_lag.toLocaleString()}
            </div>
            <p className="text-sm text-gray-600">总消费者Lag</p>
          </div>
          <div className="text-center">
            <div className={`text-2xl font-bold ${
              report.performance_summary.under_replicated_partitions > 0 ? 'text-red-500' : 'text-green-500'
            }`}>
              {report.performance_summary.under_replicated_partitions}
            </div>
            <p className="text-sm text-gray-600">副本不足分区</p>
          </div>
        </div>
      </div>

      {/* Top Topics和消费者组状态 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="bg-white rounded-lg shadow-sm border p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">Top 10 活跃Topics</h3>
          {topTopicsData.length === 0 ? (
            <div className="text-center text-gray-500 py-8">暂无活跃Topic</div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={topTopicsData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis 
                  dataKey="topic" 
                  angle={-45}
                  textAnchor="end"
                  height={80}
                />
                <YAxis />
                <Tooltip 
                  formatter={(value, name) => [
                    name === 'rate' ? `${value} msg/min` : `${value} 分区`,
                    name === 'rate' ? '生产速率' : '分区数'
                  ]}
                />
                <Bar dataKey="rate" fill="#3b82f6" />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>

        <div className="bg-white rounded-lg shadow-sm border p-6">
          <h3 className="text-lg font-medium text-gray-900 mb-4">消费者组状态分布</h3>
          {consumerGroupStatusData.length === 0 ? (
            <div className="text-center text-gray-500 py-8">暂无消费者组</div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={consumerGroupStatusData}
                  cx="50%"
                  cy="50%"
                  outerRadius={80}
                  dataKey="value"
                  label={({ name, value }) => `${name}: ${value}`}
                >
                  {consumerGroupStatusData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      {/* 问题消费者组和告警 */}
      {(report.problematic_consumer_groups.length > 0 || report.alerts.length > 0) && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {report.problematic_consumer_groups.length > 0 && (
            <div className="bg-white rounded-lg shadow-sm border p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                <AlertTriangle className="w-5 h-5 text-yellow-500 mr-2" />
                问题消费者组
              </h3>
              <div className="space-y-3">
                {report.problematic_consumer_groups.map((group, index) => (
                  <div key={index} className="border border-yellow-200 rounded-lg p-3 bg-yellow-50">
                    <div className="flex justify-between items-center">
                      <span className="font-medium">{group.group_id}</span>
                      <span className="text-sm text-gray-500">{group.state}</span>
                    </div>
                    <div className="text-sm text-gray-600 mt-1">
                      Lag: {group.total_lag.toLocaleString()} | 成员: {group.member_count}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {report.alerts.length > 0 && (
            <div className="bg-white rounded-lg shadow-sm border p-6">
              <h3 className="text-lg font-medium text-gray-900 mb-4 flex items-center">
                <AlertTriangle className="w-5 h-5 text-red-500 mr-2" />
                集群告警
              </h3>
              <div className="space-y-2">
                {report.alerts.map((alert, index) => (
                  <div key={index} className="flex items-start">
                    <AlertTriangle className="w-4 h-4 text-yellow-500 mr-2 mt-0.5 flex-shrink-0" />
                    <span className="text-sm text-gray-700">{alert}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      )}

      {/* 报告说明 */}
      <div className="bg-gray-50 rounded-lg p-6">
        <h3 className="text-lg font-medium text-gray-900 mb-3">报告说明</h3>
        <div className="space-y-2 text-sm text-gray-600">
          <p>• 本报告每分钟自动刷新，展示Kafka集群的实时监控数据</p>
          <p>• 健康分数基于副本状态、消费者Lag等指标计算</p>
          <p>• 问题消费者组指Lag超过1000条消息的消费者组</p>
          <p>• 可点击"导出报告"按钮下载完整的JSON格式报告</p>
        </div>
      </div>
    </div>
  );
};

export default MonitoringSummaryReportComponent;
